import { Scene, GameObjects, Math, Physics, Cameras, type Types } from "phaser";
import { Bird } from "./main/Bird";
import { Pipe } from "./main/Pipe";

// 场景元素：背景，地面，水管组，分数，小鸟
let background: GameObjects.TileSprite;
let floor: GameObjects.TileSprite;
let pipeGroup: Physics.Arcade.Group;
let scoreText: GameObjects.Text;
let bird: Bird;

// 数据：分数
let score: number;

export class Main extends Scene {
    constructor() {
        super("Main");
    }
    create() {
        // 创建背景和地面
        this.cameras.main.setBackgroundColor(0x825705);
        background = this.add.tileSprite(0, 0, 288, 505, "background").setOrigin(0, 0);
        floor = this.add.tileSprite(0, 393, 288, 112, "floor").setOrigin(0, 0);
        this.physics.add.existing(floor, true);

        // 创建分数
        score = 0;
        scoreText = this.add
            .text(10, 10, String(score), {
                fontSize: "36px",
                color: "#fff",
            })
            .setDepth(1);

        // 创建小鸟
        bird = new Bird(this);

        // 创建水管组
        pipeGroup = this.physics.add.group();

        // 创建两组上下水管，共4根
        let x1 = this.cameras.main.width;
        let x2 = x1 + Math.Between(150, 150);
        for (let x of [x1, x2]) {
            pipeGroup.add(new Pipe(this, x, 0));
            pipeGroup.add(new Pipe(this, x, 1));
        }
        // 设置水管无重力与水平速度
        for (let child of pipeGroup.getChildren() as Pipe[]) {
            (child.body as Physics.Arcade.Body).allowGravity = false;
            child.setVelocityX(-200);
        }

        // 注册事件
        this.addEvent();
    }
    // 注册事件
    addEvent() {
        // 小鸟与水管组重叠事件
        this.physics.add.overlap(bird, pipeGroup, () => this.gameOver("pipe_hit"));
        // 小鸟与地面碰撞事件
        this.physics.add.collider(bird, floor, () => this.gameOver("floor_hit"));
    }
    update() {
        // 瓦片元素滚动
        background.tilePositionX += 0.5;
        floor.tilePositionX += 3.4;
    }
    // 得分
    scoreAdd() {
        scoreText.setText(String(++score));
        this.sound.play("score");
    }
    // 游戏结束
    gameOver(soundKey: string) {
        this.sound.play(soundKey);
        this.sys.pause();
        this.game.scene.start("End");
    }
}
